import { RequestRs } from '../../modules/Request-rs';
import { Component, OnInit } from '@angular/core';
import {HttpParams} from '@angular/common/http';
import {ReponseRs} from '../../modules/Response-rs';
import {HttpService} from '../../share/service/http.service';
import {User} from '../../modules/user';
import { HttpAssist } from '../../share/assist/http-assist';
import { UserService } from '../../share/service/user.service';
import {Router} from '@angular/router';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
  constructor(
    private httpService: HttpService, 
    private router: Router,
    private userService: UserService
  ) { }
  // user: User = new User(1,'zs','123','qw@qw.com');
  user: User = new User();
  req: RequestRs = new RequestRs();
  res: ReponseRs = new ReponseRs();
  ngOnInit() {
  }
  /**
   * login
   * @param {User} user
   */
  login() {
    const serviceName = 'login';
    this.req.body = JSON.stringify(this.user);
    const message = JSON.stringify(this.req);
    this.httpService.postByJson<ReponseRs>(serviceName,HttpAssist.POST_BODY, message).subscribe(
      s => {
        this.res = s as ReponseRs;
        console.info(serviceName + ' ' + this.res.status);
        console.info(this.res.message);
        if (this.res.status === HttpAssist.RS_SUCCESS) {
          this.user =  JSON.parse(this.res.message);
          this.userService.setUser = this.user;
          alert('login success');
          this.router.navigate(['/home']);
        }else {
          alert('login fail, detail{' + 'code:' + this.res.status + ';message:'+ this.res.message+'}');
        }
      },
      error => {
          alert('login fail,http error in UI, detail' + error);
      }
    );
  }
  regist(){
    this.router.navigate(['/register']);
  }

  get diagnostic() { return JSON.stringify(this.user); }

}
